package com.king.myapplication;

import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

public class MainActivity extends AppCompatActivity {

    private Button button;
    private ImageView imageView;

    private int[] imgArr = {R.drawable.img1,R.drawable.img2,R.drawable.img3,
            R.drawable.img4,R.drawable.img5,R.drawable.img6,R.drawable.img7,
            R.drawable.img8};

    private int index = 0;

    Handler mHandler = new Handler();
    Runnable r = new Runnable() {

        @Override
        public void run() {
            //do something
            index++;
            if(index>=imgArr.length){
                index = 0;
            }
            imageView.setImageResource(imgArr[index]);

            //每隔3s循环执行run方法
            mHandler.postDelayed(this, 3000);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button = findViewById(R.id.nextBtn);
        imageView = findViewById(R.id.imgV);


        mHandler.postDelayed(r, 0);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                index++;
                if(index>=imgArr.length){
                    index = 0;
                }

                imageView.setImageResource(imgArr[index]);
            }
        });

    }
}
